<?php

namespace App\Http\Middleware;

use App\Http\Traits\ApiResponse;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckPermission
{
    use ApiResponse;

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string  $permission 权限编码，格式：resource.action 或 完整权限编码
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function handle(Request $request, Closure $next, string $permission): Response
    {
        $user = auth()->user();

        if (!$user) {
            return $this->unauthorized('未认证');
        }

        // 管理员拥有所有权限
        if ($user->isAdmin()) {
            return $next($request);
        }

        // 检查权限
        // 支持两种格式：resource.action 或 完整权限编码
        if (strpos($permission, '.') !== false) {
            list($resource, $action) = explode('.', $permission, 2);
            if (!$user->hasButtonPermission($resource, $action)) {
                return $this->forbidden('无权限访问');
            }
        } else {
            if (!$user->hasPermission($permission)) {
                return $this->forbidden('无权限访问');
            }
        }

        return $next($request);
    }
}

